package com.elvish.oda.busin.service;

import java.util.ArrayList;
import java.util.List;

import org.nutz.dao.QueryResult;
import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.elvish.oda.busin.dao.AreaDao;
import com.elvish.oda.busin.dao.OrganizationDao;
import com.elvish.oda.busin.pojo.Area;
import com.elvish.oda.busin.pojo.Organization;
import com.elvish.oda.common.pojo.Page;

@Component
public class OrganizationService {

	@Autowired
	private OrganizationDao organizationDao;
	@Autowired
	private AreaDao areaDao;

	public QueryResult findAll(Page page, Integer areaId) {
		List<String> ids = new ArrayList<String>();
		if (areaId != null) {
			List<Area> childrenList = areaDao.findByPid(areaId);
			// 根据id查询其下级所有数据id
			findById(childrenList, ids);
			// 自身
			ids.add(areaId.toString());
		}
		return organizationDao.findAll(page, ids.toArray(new String[ids.size()]));
	}

	public void findById(List<Area> childrenList, List<String> ids) {
		if (!Lang.isEmpty(childrenList)) {
			for (Area area : childrenList) {
				// 根据id查询pid为id的下级
				List<Area> childList = areaDao.findByPid(area.getId());
				ids.add(area.getId().toString());
				findById(childList, ids);
			}
		}
	}

	public int save(Organization organization) {
		return organizationDao.save(organization);
	}

	public int update(Organization organization) {
		return organizationDao.update(organization);
	}

	public Organization findById(Integer id) {
		return organizationDao.findById(id);
	}

	public int deleteByIds(String[] ids) {
		return organizationDao.deleteByIds(ids);
	}

}
